package com.learn.sqlsession.impl;

import com.learn.pojo.Configuration;
import com.learn.pojo.MappedStatement;
import com.learn.sqlsession.BoundSql;
import com.learn.sqlsession.Executor;
import com.learn.utils.GenericTokenParser;
import com.learn.utils.ParameterMapping;
import com.learn.utils.ParameterMappingTokenHandler;

import java.beans.IntrospectionException;
import java.beans.PropertyDescriptor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.sql.*;
import java.util.ArrayList;
import java.util.List;

public class SimpleExecutor implements Executor {
    @Override
    public <E> List<E> query(Configuration configuration, MappedStatement mappedStatement, Object... args) throws SQLException, ClassNotFoundException, NoSuchFieldException, IllegalAccessException, InstantiationException, IntrospectionException, InvocationTargetException {
        //1.注册驱动 获取连接
        Connection connection = configuration.getDataSource().getConnection();
        //2.获取SQL语句，转换SQL语句
        String sql = mappedStatement.getSql();
        BoundSql boundSql = getBoundSql(sql);
        //3.获取预处理对象PrepareStatement
        PreparedStatement preparedStatement = connection.prepareStatement(boundSql.getSqlText());
        //4.设置参数
        String parameterType = mappedStatement.getParameterType();
        Class<?> parameterTypeClass = getClassType(parameterType);
        List<ParameterMapping> parameterMappingList = boundSql.getParameterMappingList();
        for (int i = 0; i < parameterMappingList.size(); i++) {
            ParameterMapping mapping = parameterMappingList.get(i);
            String context = mapping.getContent();
            //暴力访问
            Field field = parameterTypeClass.getDeclaredField(context);
            field.setAccessible(true);
            Object o = field.get(args[0]);
            preparedStatement.setObject(i + 1, o);
        }
        //5.执行SQL
        ResultSet resultSet = preparedStatement.executeQuery();
        String resultType = mappedStatement.getResultType();
        Class<?> resultTypeClass = getClassType(resultType);
        ArrayList<Object> list = new ArrayList<>();
        while (resultSet.next()) {
            Object o = resultTypeClass.newInstance();
            //获取结果集元数据
            ResultSetMetaData metaData = resultSet.getMetaData();
            for (int i = 1; i <= metaData.getColumnCount(); i++) {
                //获取字段名
                String name = metaData.getColumnName(i);
                //获取字段值
                Object value = resultSet.getObject(i);
                //使用反射和内省，完成封装
                PropertyDescriptor propertyDescriptor = new PropertyDescriptor(name, resultTypeClass);
                Method writeMethod = propertyDescriptor.getWriteMethod();
                writeMethod.invoke(o, value);
            }
            list.add(o);
        }
        //6.封装返回结果集
        return (List<E>) list;
    }

    public BoundSql getBoundSql(String sql) {
        //1.将#{}用?代替
        ParameterMappingTokenHandler tokenHandler = new ParameterMappingTokenHandler();
        GenericTokenParser tokenParser = new GenericTokenParser("#{", "}", tokenHandler);
        String parsedSql = tokenParser.parse(sql);
        // 2.解析出#{}中的值进行存储
        List<ParameterMapping> parameterMappingList = tokenHandler.getParameterMappings();
        BoundSql boundSql = new BoundSql(parsedSql, parameterMappingList);
        return boundSql;
    }

    public Class<?> getClassType(String parameterType) throws ClassNotFoundException {
        if (parameterType != null) {
            return Class.forName(parameterType);
        }
        return null;
    }
}
